package com.usefullc.user.controller;


import com.usefullc.common.constants.SystemConstant;
import com.usefullc.common.enums.RegisterTypeEnum;
import com.usefullc.common.exception.BizException;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.entity.WebResult;
import com.usefullc.common.enums.SmsCodeTypeEnum;
import com.usefullc.common.enums.UserStatusEnum;
import com.usefullc.common.enums.UserTypeEnum;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.system.controller.WebResultBuilder;
import com.usefullc.system.param.IdsParam;
import com.usefullc.system.service.component.ImgCodeComponent;
import com.usefullc.system.service.component.SmsComponent;
import com.usefullc.system.service.component.SystemConfigComponent;
import com.usefullc.user.domain.Dept;
import com.usefullc.user.domain.Position;
import com.usefullc.user.domain.Role;
import com.usefullc.user.domain.User;
import com.usefullc.user.param.*;
import com.usefullc.user.query.UserQuery;
import com.usefullc.user.service.EmployeeService;
import com.usefullc.user.service.UserService;
import com.usefullc.user.service.component.UserManager;
import com.usefullc.user.vo.LoginResultVo;
import com.usefullc.user.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Sampson
 * @date: 2022-03-19 12:02
 */
@RestController
@RequestMapping(path = "/user/user/")
@Api(tags = "后台用户管理")
public class UserController {

    @Autowired
    private ImgCodeComponent imgCodeComponent;

    @Autowired
    private SmsComponent smsComponent;

    @Autowired
    private UserService userService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private SystemConfigComponent systemConfigComponent;

    @ApiOperation(value = "获取图形验证码",  response = WebResult.class)
    @GetMapping(path = "getImgCode", produces = "application/json")
    public WebResult getImgCode(HttpServletRequest request) {
        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
        String imgCode = imgCodeComponent.getImgCode(SmsCodeTypeEnum.LOGIN.getCode(), UserTypeEnum.ADMIN.getCode(), deviceId);
        return WebResultBuilder.successResult(imgCode);
    }

    @ApiOperation(value = "获取短信验证码",  response = WebResult.class)
    @GetMapping(path = "getSmsCode", produces = "application/json")
    public WebResult getSmsCode(UserLoginParam param) {
//        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
        smsComponent.getImgCode(param.getCheckCodeType(),UserTypeEnum.ADMIN.getCode(),"86",param.getMobile());
        return WebResultBuilder.successResult();
    }


//    @ApiOperation(value = "获取忘记密码短信验证码",  response = WebResult.class)
//    @GetMapping(path = "getForgetPwdSmsCode", produces = "application/json")
//    public WebResult getForgetPwdSmsCode(UserLoginParam param) {
////        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
//        smsComponent.getImgCode(SmsCodeTypeEnum.FORGET_PASSWORD.getCode(),UserTypeEnum.ADMIN.getCode(),"86",param.getMobile());
//        return WebResultBuilder.successResult();
//    }






    @ApiOperation(value = "获取当前登录用户信息",  response = WebResult.class)
    @GetMapping(path = "getLoginUserInfo", produces = "application/json")
    public WebResult getLoginUserInfo(HttpServletRequest request) {
        UserVo user = userService.getLoginUser(request);
        return WebResultBuilder.successResult(user);
    }

    @ApiOperation(value = "用户分页列表", response = WebResult.class)
    @GetMapping(path = "list", produces = "application/json")
    public WebResult list(UserQuery query) {
//        query.setType(UserTypeEnum.ADMIN.getCode());
        Pager<UserVo> page = userService.findVoByPage(query);
        return WebResultBuilder.successResult(page);
    }

    @ApiOperation(value = "用户详情", response = WebResult.class)
    @GetMapping(path = "detail", produces = "application/json")
    public WebResult detail(@ApiParam(value = "用户ID", required = true, example = "1") @Valid @RequestParam Long id) {
        User user = userService.findById(id);
        return WebResultBuilder.successResult(user);
    }


    @ApiOperation(value = "根据短信验证码修改忘记密码", response = WebResult.class)
    @PostMapping(path = "updateForgetLoginPwdBySmsCode", produces = "application/json")
    public WebResult updateForgetLoginPwdBySmsCode(@RequestBody UserLoginParam param, HttpServletRequest request) {
//        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
        userService.updateForgetLoginPwdBySmsCode(UserTypeEnum.ADMIN.getCode(), "86",param.getMobile(),  param.getCheckCode(),param.getPwd());
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "检查账户或手机号是否唯一",  response = WebResult.class)
    @PostMapping(path = "checkUserUnique", produces = "application/json")
    public WebResult checkUserUnique(@RequestBody UserRegisterParam param) {
        if(StringUtils.isNotEmpty(param.getAccountNo())){
            boolean unique = this.userService.checkUserUniqueByAccountNo(UserTypeEnum.ADMIN.getCode(), param.getAccountNo());
            if(!unique){
                throw new BizException("账号已存在");
            }
        }else if(StringUtils.isNotEmpty(param.getMobile())){
            boolean unique = this.userService.checkUserUniqueByMobile(UserTypeEnum.ADMIN.getCode(), param.getMobile());
            if(!unique){
                throw new BizException("手机号码已存在");
            }
        }
        return WebResultBuilder.successResult();
    }



    @ApiOperation(value = "用户登录[密码]", response = WebResult.class)
    @PostMapping(path = "login", produces = "application/json")
    public WebResult login(@RequestBody UserAdminLoginParam param, HttpServletRequest request) {
        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
        User user = userService.loginByPwd(UserTypeEnum.ADMIN.getCode(), param.getAccountNo(), param.getPwd(), param.getImgCode(), deviceId);
        String token = userService.resetLoginToken(user);
        LoginResultVo loginResultVo = new LoginResultVo();
        loginResultVo.setToken(token);
        UserVo userVo = BeanUtils.beanCopy(user, UserVo.class);
        loginResultVo.setUserInfo(userVo);
        return WebResultBuilder.successResult(loginResultVo);
    }


    @ApiOperation(value = "用户登录[验证码]", response = WebResult.class)
    @PostMapping(path = "loginByMobile", produces = "application/json")
    public WebResult loginByMobile(@RequestBody UserLoginParam param, HttpServletRequest request) {
//        String deviceId = request.getHeader(SystemConstant.DEVICE_ID);
//        User user = userService.loginByPwd(UserTypeEnum.ADMIN.getCode(), param.getAccountNo(), param.getPwd(), param.getImgCode(), deviceId);
        User user = userService.loginBySmsCode(UserTypeEnum.ADMIN.getCode(), "86", param.getMobile(), param.getCheckCode());
        String token = userService.resetLoginToken(user);
        LoginResultVo loginResultVo = new LoginResultVo();
        loginResultVo.setToken(token);
        UserVo userVo = BeanUtils.beanCopy(user, UserVo.class);
        loginResultVo.setUserInfo(userVo);
        return WebResultBuilder.successResult(loginResultVo);
    }


    @ApiOperation(value = "用户注册", response = WebResult.class)
    @PostMapping(path = "register", produces = "application/json")
    public WebResult register(@RequestBody UserRegisterParam param) {
        param.setUserType(UserTypeEnum.ADMIN.getCode());
        param.setRegisterType(RegisterTypeEnum.MOBILE.getCode());
        param.setAreaCode("86");
        userService.register(param);
        return WebResultBuilder.successResult();
    }


    @ApiOperation(value = "用户注销",  response = WebResult.class)
    @PostMapping(path = "logout", produces = "application/json")
    public WebResult logout(HttpServletRequest request) {
        userService.clearLoginUser(request);
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "保存用户", response = WebResult.class)
    @PostMapping(path = "save", produces = "application/json")
    public WebResult save(@Valid @RequestBody UserEditParam param) {
        User user = BeanUtils.beanCopy(param, User.class);
        saveUser(user,param);
        return WebResultBuilder.successResult(user);
    }

    private void saveUser(User user,UserEditParam param){
        user.setType(UserTypeEnum.ADMIN.getCode());
        List<Long> roleIds = param.getRoleIds();
        if (CollectionUtils.isNotEmpty(roleIds)) {
            List<Role> roleList = new ArrayList<>();
            for (Long roleId : roleIds) {
                Role role = new Role();
                role.setId(roleId);
                roleList.add(role);
            }
            user.setRoleList(roleList);
        }
        if(param.getPositionId() != null){
            Position position = new Position();
            position.setId(param.getPositionId());
            user.setPosition(position);
        }

        if(param.getDeptId() != null){
            Dept dept = new Dept();
            dept.setId(param.getDeptId());
            user.setDept(dept);
        }
        user.setStatus(UserStatusEnum.PASS.getCode());
        userService.save(user);
    }

    @ApiOperation(value = "修改用户", response = WebResult.class)
    @PostMapping(path = "update", produces = "application/json")
    public WebResult update(@Valid @RequestBody UserEditParam param) {
        User user = this.userService.findById(param.getId());
        BeanUtils.beanCopy(param,user);
        saveUser(user,param);
        return save(param);
    }


    @ApiOperation(value = "绑定员工", response = WebResult.class)
    @PostMapping(path = "bingEmployee", produces = "application/json")
    public WebResult bingEmployee(@Valid @RequestBody BindEmployeeParam param) {
        EmployeeEditParam employeeEditParam = BeanUtils.beanCopy(param, EmployeeEditParam.class);
        employeeService.saveEmployee(employeeEditParam);
        return WebResultBuilder.successResult();
    }


    @ApiOperation(value = "删除用户", response = WebResult.class)
    @PostMapping(path = "del", produces = "application/json")
    public WebResult del(@RequestBody IdsParam idsParam) {
        userService.deletePhysByIds(idsParam.getIds());
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "自己修改密码", response = WebResult.class)
    @PostMapping(path = "updatePwd", produces = "application/json")
    public WebResult updatePwd(@Valid @RequestBody UpdatePwdParam param) {
        UserVo loginUser = UserManager.getLoginUser();
        userService.updatePwd(loginUser.getId(), param.getOldPwd(), param.getNewPwd());
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "管理员重置密码", response = WebResult.class)
    @PostMapping(path = "resetPwd", produces = "application/json")
    public WebResult resetPwd(@RequestBody IdsParam param) {
        String pwd = userService.resetPwd(param.getIds());
        return WebResultBuilder.successResult(pwd);
    }


    @ApiOperation(value = "冻结", response = WebResult.class)
    @PostMapping(path = "freeze", produces = "application/json")
    public WebResult freeze(@RequestBody IdsParam idsParam) {
        userService.updateAllStatus(idsParam.getIds(), UserStatusEnum.NOT_PASS.getCode());
        return WebResultBuilder.successResult();
    }

    @ApiOperation(value = "解冻", response = WebResult.class)
    @PostMapping(path = "unFreeze", produces = "application/json")
    public WebResult unFreeze(@RequestBody IdsParam idsParam) {
        userService.updateAllStatus(idsParam.getIds(), UserStatusEnum.PASS.getCode());
        return WebResultBuilder.successResult();
    }



}
